<template>
  <el-dialog
    v-model="visible"
    :title="dialogTitle"
    width="800px"
    :before-close="handleClose"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <el-form
      ref="formRef"
      :model="intoutStore"
      :rules="rules"
      label-width="120px"
      class="inbound-form"
      :label-position="'right'"
      :validate-on-rule-change="false"
    >
      <el-row :gutter="20">
        <!-- 左列 -->
        <el-col :span="12">
          <!-- 单号 -->
          <el-form-item :label="numberLabel" prop="inStoreNo" required>
            <el-input
              v-model="intoutStore.inStoreNo"
              :placeholder="numberPlaceholder"
              disabled
            />
          </el-form-item>

                     <!-- 仓库名称 -->
           <el-form-item label="仓库名称" prop="storeId" required>
             <div class="warehouse-select-container">
               <el-select
                 v-model="intoutStore.storeId"
                 placeholder="请选择"
                 style="width: 255px"
               >
                 <el-option
                   v-for="item in storedata"
                   :key="item.id"
                   :label="item.storeName"
                   :value="item.id"
                 />
               </el-select>
               <el-button type="text" class="settings-btn" @click="handleWarehouseSettings">
                 设置
               </el-button>
             </div>
           </el-form-item>

          <!-- 关联单号 -->
          <el-form-item label="关联单号" prop="inventoryId">
            <el-input
              v-model="intoutStore.inventoryId"
              placeholder="请输入关联单号"
              disabled
            />
          </el-form-item>

          <!-- 备注/出库原因 -->
          <el-form-item v-if="isOutbound" :label="remarkLabel" prop="reson">
            <el-input
              v-model="intoutStore.reson"
              type="textarea"
              :rows="3"
              placeholder="请输入出库原因"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>

        <!-- 右列 -->
        <el-col :span="12">
          <!-- 日期 -->
          <el-form-item :label="dateLabel" prop="intOutStoreTime" required>
            <el-date-picker
              v-model="intoutStore.intOutStoreTime"
              type="date"
              placeholder="请选择"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

                     <!-- 经办人 -->
           <el-form-item label="经办人" prop="attnName">
             <el-input
               v-model="intoutStore.attnName"
               placeholder="请选择"
               readonly
               @click="openJing"
             >
               <template #suffix>
                 <el-icon class="el-input__icon">
                   <MoreFilled />
                 </el-icon>
               </template>
             </el-input>
           </el-form-item>
        </el-col>
             </el-row>
     </el-form>

     <!-- 选中的货品信息 -->
     <div v-if="props.selectedGoods && props.selectedGoods.length > 0" class="selected-goods-info">
       <h4>选中的货品 ({{ props.selectedGoods.length }}项) - 库存将同步更新</h4>
       <el-table :data="props.selectedGoods" size="small" border>
         <el-table-column prop="goodsName" label="货品名称" />
         <el-table-column prop="goodsNumber" label="货品编号" />
         <el-table-column prop="systemNum" label="当前系统库存" />
         <el-table-column prop="actualNum" label="实际盘点数量" />
         <el-table-column prop="differentCount" label="差异数量">
           <template v-slot="scoped">
             <span :class="getDifferenceClass(scoped.row.differentCount)">
               {{ scoped.row.differentCount || 0 }}
             </span>
           </template>
         </el-table-column>
       </el-table>
       <el-alert
         type="info"
         :closable="false"
         show-icon
         style="margin-top: 10px;"
       >
         <template #title>
           提示：确认后将自动更新系统库存
         </template>
         确认操作后，选中商品的系统库存将自动更新为手动输入的实际盘点数量，差异数量将归零。
         <div style="margin-top: 8px; font-size: 12px;">
           <strong>差异数组字符串：</strong>{{ getDifferentCountString() }}
         </div>
         <div style="margin-top: 4px; font-size: 12px;">
           <strong>实际库存数组：</strong>{{ getActualNumString() }}
         </div>
       </el-alert>
     </div>

    

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>


  <!-- 经办人 -->
  <el-dialog v-model="dialogTableVisible" title="经办人" width="800" draggable align-center>
    <el-table :data="tableData">
       <el-table-column fixed type="index" label="序号" width="60px" />
            <el-table-column prop="userName" label="用户"  />
            <el-table-column prop="roleName" label="角色" width="200px"/>
            <el-table-column prop="sex" label="性别" >
                <template v-slot="scoped">
                    <el-tag type="primary" v-if="scoped.row.sex==false">男</el-tag>
                    <el-tag type="danger" v-if="scoped.row.sex==true">女</el-tag>
                </template>
            </el-table-column>
            <el-table-column fixed="right" prop="address" label="操作" width="160">
                <template v-slot="scoped">
                    <el-button type="warning" @click="dispose(scoped.row)" round>选择</el-button>
                </template>
            </el-table-column>
    </el-table>
    <div class="demo-pagination-block" style="margin-top: 20px;">
            <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.listcount"
            />
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onUnmounted, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MoreFilled } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { inventoryRead, inventoryWrite, readBasic } from '@/Helper/axiosSetting'
import { useRouter } from 'vue-router'
import {useCounterStore} from '@/stores/counter'
import { globalStatisticsPushService } from '@/services/GlobalStatisticsPushService'
const router=useRouter();

// 处理统计数据推送的辅助函数
async function handleStatisticsPush(operationType: 'inbound' | 'outbound') {
  try {
    const operation = operationType === 'inbound' ? '入库' : '出库'
    const pushSuccess = await globalStatisticsPushService.triggerInventoryOperationPush(
      operationType,
      intoutStore.goodsName || '未知商品',
      intoutStore.goodsNum || 0,
      use.UserInfo.UserName || '未知用户'
    )
    
    if (pushSuccess) {
      console.log(`✅ ${operation}操作后统计数据推送成功`)
    } else {
      console.warn(`⚠️ ${operation}操作后统计数据推送失败`)
    }
  } catch (error) {
    console.error(`❌ ${operationType === 'inbound' ? '入库' : '出库'}操作后推送失败:`, error)
  }
}

onMounted(()=>{
  getstoredata()
})

// 定义props
interface Props {
  modelValue: boolean
  inventoryData?: any
  mode?: 'inbound' | 'outbound' // 新增模式参数
  selectedGoods?: any[] // 选中的货品
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  inventoryData: () => ({}),
  mode: 'inbound',
  selectedGoods: () => []
})

// 定义emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'submit': [data: any]
}>()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const formRef = ref<FormInstance>()

// 计算属性
const isOutbound = computed(() => props.mode === 'outbound')
const dialogTitle = computed(() => isOutbound.value ? '出库信息' : '入库信息')
const numberLabel = computed(() => isOutbound.value ? '出库单号' : '入库单号')
const numberPlaceholder = computed(() => isOutbound.value ? '自动获取系统编号' : '自动获取系统编号')
const dateLabel = computed(() => isOutbound.value ? '出库日期' : '入库日期')
const remarkLabel = computed(() => isOutbound.value ? '出库原因' : '备注')
const use=useCounterStore();
// 获取当前选中的仓库名称
const selectedWarehouseName = computed(() => {
  const selectedWarehouse = storedata.value.find(item => item.id === intoutStore.storeId)
  return selectedWarehouse?.storeName || ''
})

// 仓库选项 - 动态获取
const storedata = ref<any[]>([])

const getstoredata = () => {
  inventoryRead.get("/api/InventoryRead/GetStoreList").then(res => {
    storedata.value = res.data.data.list || []
    console.log('获取到的仓库数据:', storedata.value)
  }).catch(error => {
    console.error('获取仓库数据失败:', error)
    ElMessage.error('获取仓库数据失败')
  })
}


//出入库单表单数据
const intoutStore=reactive({
    "inventoryId": "",
  "inStoreNo": "",
  "goodsIds": "",
  "storeId": 0,
  "count": 0,
  "reson": "",
  "differentCount":'',
  "actualNums": '',
  "isIntOrOut": true,
  "attnId": 0,
  "attnName": "",
  "createUserName": "",
  "intOutStoreTime": ""
})


//确定经办人
const tableData= ref([])
const page=reactive({
    PageIndex:1,
    PageSize:5,
    listcount:0
})
watch(page,()=>{
    getUserList()
},{deep:true})
const getUserList=()=>{
    readBasic.get("api/Manage/GetUserList",{params:{
        PageIndex:page.PageIndex,
        PageSize:page.PageSize
    }}).then(res=>{
        tableData.value=res.data.data.list
        page.listcount=res.data.data.recordCount
    })
}

const dialogTableVisible = ref(false)

const openJing=()=>{
  dialogTableVisible.value=true
  getUserList()
}
//确定经办人
const dispose = (row: any) => {
  intoutStore.attnId = row.id
  intoutStore.attnName = row.userName
  dialogTableVisible.value = false
}


// 表单验证规则
const rules: FormRules = {
  storeId: [
    { required: true, message: '请选择仓库名称', trigger: 'change' }
  ],
  intOutStoreTime: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  attnName: [
    { required: true, message: '请选择经办人', trigger: 'change' }
  ]
}

// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    // 确保仓库数据已加载
    if (storedata.value.length === 0) {
      getstoredata()
    }
    nextTick(() => {
      initFormData()
    })
  }
})

// 监听visible变化
watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 监听选中货品变化，更新goodsIds、Count和DifferentCount
watch(() => props.selectedGoods, (newSelectedGoods) => {
  if (newSelectedGoods && newSelectedGoods.length > 0) {
    // 提取所有选中货品的ID并转换为字符串
    const goodsIds = newSelectedGoods.map(goods => goods.id || goods.goodsId).join(',')
    intoutStore.goodsIds = goodsIds
    console.log('更新goodsIds:', goodsIds)
    
    // 获取每个货品的差异值，组成数组字符串
    const differentCounts = newSelectedGoods.map(goods => {
      const differentCount = goods.differentCount || 0
      return differentCount.toString()
    })
    intoutStore.differentCount = differentCounts.join(',')
    console.log('更新differentCount:', intoutStore.differentCount)
    
    // 获取每个货品的实际库存值，组成数组字符串
    const actualNums = newSelectedGoods.map(goods => {
      const actualNum = goods.actualNum || 0
      return actualNum.toString()
    })
    intoutStore.actualNums = actualNums.join(',')
    console.log('更新actualNums:', intoutStore.actualNums)
    
    // 计算所有选中货品的差异值总和
    const totalCount = newSelectedGoods.reduce((sum, goods) => {
      const differentCount = goods.differentCount || 0
      return sum + Math.abs(differentCount) // 使用绝对值，因为差异值可能为负数
    }, 0)
    intoutStore.count = totalCount
    console.log('更新Count:', totalCount)
    
    // 打印详细的货品差异信息
    console.log('货品差异详情:')
    newSelectedGoods.forEach((goods, index) => {
      console.log(`  货品${index + 1}: ID=${goods.id}, 名称=${goods.goodsName}, 差异=${goods.differentCount}`)
    })
  } else {
    // 如果没有选中货品，清空相关字段
    intoutStore.goodsIds = ''
    intoutStore.differentCount = ''
    intoutStore.actualNums = ''
    intoutStore.count = 0
  }
}, { immediate: true, deep: true })

// 初始化表单数据
const initFormData = () => {
  // 生成单号
  intoutStore.inStoreNo = generateOrderNumber()
  
  // 设置关联单号（从盘点数据中获取）
  if (props.inventoryData?.inventoryNnumber) {
    intoutStore.inventoryId = props.inventoryData.inventoryNnumber
  }
  
  // 设置默认日期为今天
  intoutStore.intOutStoreTime = new Date().toISOString().split('T')[0]
  
  // 设置默认经办人
  if (props.inventoryData?.attnName) {
    intoutStore.attnName = props.inventoryData.attnName
  }
  
  // 根据模式设置isIntOrOut
  intoutStore.isIntOrOut = !isOutbound.value // true为入库，false为出库
  
  // 设置默认仓库名称（从盘点数据中获取）
  if (props.inventoryData?.storeName) {
    console.log('盘点数据中的仓库名称:', props.inventoryData.storeName)
    // 根据仓库名称找到对应的选项值
    const warehouseOption = storedata.value.find(option => 
      option.storeName === props.inventoryData.storeName
    )
    if (warehouseOption) {
      intoutStore.storeId = warehouseOption.id
      console.log('找到匹配的仓库选项:', warehouseOption)
    } else {
      // 如果找不到匹配的选项，尝试根据storeId匹配
      if (props.inventoryData?.storeId) {
        const storeIdOption = storedata.value.find(option => 
          option.id === props.inventoryData.storeId
        )
        if (storeIdOption) {
          intoutStore.storeId = storeIdOption.id
          console.log('根据storeId找到匹配的仓库选项:', storeIdOption)
        } else {
          // 如果还是找不到，设置为第一个选项
          intoutStore.storeId = storedata.value[0]?.id || 0
          console.log('未找到匹配的仓库选项，使用默认值:', intoutStore.storeId)
        }
      } else {
        // 如果找不到匹配的选项，设置为第一个选项
        intoutStore.storeId = storedata.value[0]?.id || 0
        console.log('未找到匹配的仓库选项，使用默认值:', intoutStore.storeId)
      }
    }
  } else {
    // 如果没有仓库名称，设置为第一个选项
    intoutStore.storeId = storedata.value[0]?.id || 0
    console.log('没有仓库名称，使用默认值:', intoutStore.storeId)
  }
  
  // 清空备注
  intoutStore.reson = ''
  
  // 初始化goodsIds和Count（从选中的货品中获取）
  if (props.selectedGoods && props.selectedGoods.length > 0) {
    const goodsIds = props.selectedGoods.map(goods => goods.id || goods.goodsId).join(',')
    intoutStore.goodsIds = goodsIds
    console.log('初始化goodsIds:', goodsIds)
    
    // 计算所有选中货品的差异值总和
    const totalCount = props.selectedGoods.reduce((sum, goods) => {
      const differentCount = goods.differentCount || 0
      return sum + Math.abs(differentCount) // 使用绝对值，因为差异值可能为负数
    }, 0)
    intoutStore.count = totalCount
    console.log('初始化Count:', totalCount)
  } else {
    intoutStore.goodsIds = ''
    intoutStore.count = 0
  }
}

// 生成单号
const generateOrderNumber = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  const prefix = isOutbound.value ? 'CK' : 'RK' // CK为出库，RK为入库
  return `${prefix}${year}${month}${day}${random}`
}

// 处理仓库设置
const handleWarehouseSettings = () => {
  ElMessage.info('仓库设置功能开发中...')
}



// 处理关闭对话框
const handleClose = () => {
  ElMessageBox.confirm('确认关闭对话框吗？未保存的数据将丢失', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    visible.value = false
    resetForm()
  }).catch(() => {
    // 用户取消关闭
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(intoutStore, {
    inventoryId: '',
    inStoreNo: '',
    goodsIds: '',
    storeId: storedata.value[0]?.id || 0,
    count: 0,
    differentCount:'',
    reson: '',
    isIntOrOut: !isOutbound.value, // 根据模式设置：true为入库，false为出库
    attnId: 0,
    attnName: '',
    createUserName: '',
    intOutStoreTime: ''
  })
}

// 获取差异数量样式
const getDifferenceClass = (value: any) => {
  if (value > 0) return 'text-green'
  if (value < 0) return 'text-red'
  return ''
}

// 获取差异数量数组字符串
const getDifferentCountString = () => {
  if (!props.selectedGoods || props.selectedGoods.length === 0) {
    return '无选中货品'
  }
  
  const differentCounts = props.selectedGoods.map(goods => {
    const differentCount = goods.differentCount || 0
    return differentCount.toString()
  })
  
  return `[${differentCounts.join(', ')}]`
}

// 获取实际库存数组字符串
const getActualNumString = () => {
  if (!props.selectedGoods || props.selectedGoods.length === 0) {
    return '无选中货品'
  }
  
  const actualNums = props.selectedGoods.map(goods => {
    const actualNum = goods.actualNum || 0
    return actualNum.toString()
  })
  
  return `[${actualNums.join(', ')}]`
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    // 调试：打印提交前的数据
    console.log('=== 提交数据调试信息 ===')
    console.log('选中货品数量:', props.selectedGoods?.length || 0)
    console.log('货品ID字符串:', intoutStore.goodsIds)
    console.log('差异数量字符串:', intoutStore.differentCount)
    console.log('实际库存字符串:', intoutStore.actualNums)
    console.log('操作类型:', intoutStore.isIntOrOut ? '入库' : '出库')
    
    // 打印每个选中货品的详细信息，特别是手动输入的实际库存
    if (props.selectedGoods && props.selectedGoods.length > 0) {
      console.log('选中货品详细信息:')
      props.selectedGoods.forEach((goods, index) => {
        console.log(`  货品${index + 1}:`)
        console.log(`    ID: ${goods.id}`)
        console.log(`    名称: ${goods.goodsName}`)
        console.log(`    原系统库存: ${goods.systemNum}`)
        console.log(`    手动输入实际库存: ${goods.actualNum}`)
        console.log(`    差异: ${goods.differentCount}`)
      })
    }
    
    console.log('提交的完整数据:', JSON.stringify(intoutStore, null, 2))
    console.log('========================')
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const operationType = isOutbound.value ? '出库' : '入库'
    intoutStore.createUserName=use.UserInfo.UserName
    if(intoutStore.isIntOrOut==true){//入库
      inventoryWrite.post("/api/InventoryWrite/AddintoutStore",intoutStore).then(async res=>{
        if(res.data.code==200){
          // 显示成功消息
          ElMessage.success({
            message: res.data.message,
            duration: 3000
          })
          
          // 触发全量统计数据推送给所有在线用户
          await handleStatisticsPush('inbound')
          
          // 发送事件通知父组件刷新数据
          emit('submit', {
            operationType: '入库',
            success: true,
            data: intoutStore
          })
          
          router.push({
            path:'/InventoryTask'
          })
        }else{
          ElMessage.error('入库操作失败：' + (res.data.message || '未知错误'))
        }
      }).catch(error => {
        console.error('入库请求失败:', error)
        ElMessage.error('入库操作失败，请稍后重试')
      })

    }
    if(intoutStore.isIntOrOut==false){//出库
      inventoryWrite.post("/api/InventoryWrite/AddintoutStore",intoutStore).then(async res=>{
        if(res.data.code==200){
          // 显示成功消息
          ElMessage.success({
            message: res.data.message,
            duration: 3000
          })
          
          // 触发全量统计数据推送给所有在线用户
          await handleStatisticsPush('outbound')
          
          // 发送事件通知父组件刷新数据
          emit('submit', {
            operationType: '出库',
            success: true,
            data: intoutStore
          })
          
          router.push({
            path:'/InventoryTask'
          })
        }else{
          ElMessage.error('出库操作失败：' + (res.data.message || '未知错误'))
        }
      }).catch(error => {
        console.error('出库请求失败:', error)
        ElMessage.error('出库操作失败，请稍后重试')
      })

    }
    visible.value = false
    resetForm()
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 组件卸载时清理表单引用
onUnmounted(() => {
  if (formRef.value) {
    formRef.value.clearValidate()
  }
})
</script>

<style scoped>
.inbound-form {
  padding: 20px 0;
}

.warehouse-select-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.settings-btn {
  color: #67c23a;
  font-size: 12px;
  padding: 0;
  height: auto;
  flex-shrink: 0;
}

.settings-btn:hover {
  color: #85ce61;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  min-width: 120px;
  text-align: right;
}

:deep(.el-form-item.is-required .el-form-item__label::before) {
  color: #f56c6c;
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: #f5f7fa;
  color: #606266;
}

:deep(.el-form-item__content) {
  flex: 1;
  min-width: 0;
}

.selected-goods-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.selected-goods-info h4 {
  margin: 0 0 10px 0;
  color: #495057;
  font-size: 14px;
  font-weight: 600;
}

.text-red {
  color: #f56c6c !important;
}

.text-green {
  color: #67c23a !important;
}
</style> 